package com.redrose.videodemo.service;

import android.accessibilityservice.AccessibilityService;
import android.accessibilityservice.AccessibilityServiceInfo;
import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.text.TextUtils;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;

import com.redrose.videodemo.bean.Photo;
import com.redrose.videodemo.utils.EventBusMessage;
import com.redrose.videodemo.utils.GlobalData;
import com.redrose.videodemo.utils.LogUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

public class AccessibilitySampleService extends AccessibilityService {
    private static final String douyinMainClassName = "com.ss.android.ugc.aweme.main.MainActivity";
    private static final String videoRecordNewActivity = "com.ss.android.ugc.aweme.shortvideo.ui.VideoRecordNewActivity";
    private static final String chooseMediaActivity = "com.ss.android.ugc.aweme.shortvideo.local.ChooseMediaActivity";
    private static final String cutMultiVideo = "com.ss.android.ugc.aweme.shortvideo.cut.CutMultiVideoActivity";
    private static final String aIMusicVEVideoPublish = "com.ss.android.ugc.aweme.shortvideo.edit.AIMusicVEVideoPublishEditActivity";
    private static final String videoPublishActivity = "com.ss.android.ugc.aweme.shortvideo.ui.VideoPublishActivity";
    private static final String duokaifenshenMain = "com.bly.dkplat.widget.MainActivity";
    private static final String pluginConfigActivity = "com.bly.dkplat.widget.manage.PluginConfigActivity";
    public static final String TAG = "AccessibilitySampleService";

    @Override
    protected void onServiceConnected() {
        super.onServiceConnected();
        LogUtils.e(TAG, "--onServiceConnected---");
        AccessibilityServiceInfo info = new AccessibilityServiceInfo();
        info.eventTypes = AccessibilityEvent.TYPES_ALL_MASK;
        info.feedbackType = AccessibilityServiceInfo.FEEDBACK_GENERIC;
        info.notificationTimeout = 100;
        info.packageNames = new String[]{"com.ss.android.ugc.aweme", "com.bly.dkplat"};
        info.flags = AccessibilityServiceInfo.FLAG_REPORT_VIEW_IDS;
        setServiceInfo(info);


    }

    @Override
    public void onAccessibilityEvent(AccessibilityEvent event) {
        // 此方法是在主线程中回调过来的，所以消息是阻塞执行的
        // 获取包名
        if (!GlobalData.isPause) {
            String pkgName = event.getPackageName().toString();
            String currentActivityName = event.getClassName().toString();
            int eventType = event.getEventType();
            AccessibilityNodeInfo rootInActiveWindow = getRootInActiveWindow();
            if (rootInActiveWindow != null) {
                switch (eventType) {
                    case AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED:
                        LogUtils.e(pkgName + " \t" + currentActivityName);
                        if (douyinMainClassName.equals(currentActivityName)) {
                            if (rootInActiveWindow != null) {
                                List<AccessibilityNodeInfo> bottomRootNodeInfo = rootInActiveWindow.findAccessibilityNodeInfosByViewId("com.ss.android.ugc.aweme:id/ap2");
                                int size = bottomRootNodeInfo.size();
                                if (size == 1) {
                                    //拿到底部菜单栏父容器
                                    AccessibilityNodeInfo bottomFrameLayout = bottomRootNodeInfo.get(0);
                                    int count = bottomFrameLayout.getChildCount();
                                    if (count == 5) {
                                        AccessibilityNodeInfo addVideoFrameLayout = bottomFrameLayout.getChild(2);
                                        if (addVideoFrameLayout.isClickable()) {
                                            performViewClick(addVideoFrameLayout);
                                        }
                                    }
                                }
                            }

                        } else if (videoRecordNewActivity.equals(currentActivityName)) {
                            List<AccessibilityNodeInfo> imageListRootInfo = rootInActiveWindow.findAccessibilityNodeInfosByViewId("com.ss.android.ugc.aweme:id/c15");
                            int num = imageListRootInfo.size();
                            if (num == 1) {
                                AccessibilityNodeInfo openImage = imageListRootInfo.get(0);
                                if (openImage.isClickable()) {
                                    performViewClick(openImage);
                                }
                            }

                        } else if (chooseMediaActivity.equals(currentActivityName)) {
//                        rootInActiveWindow.findAccessibilityNodeInfosByViewId()
                            List<AccessibilityNodeInfo> videoListItem = rootInActiveWindow.findAccessibilityNodeInfosByText("视频");
                            AccessibilityNodeInfo videoText = rootInActiveWindow.getChild(2);
                            performViewClick(videoText);
                        } else if (cutMultiVideo.equals(currentActivityName)) {
                            LogUtils.e(pkgName + " \t" + currentActivityName);
                            int num = rootInActiveWindow.getChildCount();
                            if (num >= 10) {
                                AccessibilityNodeInfo nextTextView = rootInActiveWindow.getChild(2);
                                performViewClick(nextTextView);
                            }
                        } else if (aIMusicVEVideoPublish.equals(currentActivityName)) {
                            LogUtils.e(pkgName + " \t" + currentActivityName);
                            int num = rootInActiveWindow.getChildCount();
                            if (num >= 8) {
                                AccessibilityNodeInfo nextTextView = rootInActiveWindow.getChild(7);
                                if ("com.ss.android.ugc.aweme:id/s2".equals(nextTextView.getViewIdResourceName())) {
                                    performViewClick(nextTextView);
                                }
                            }
                        } else if (videoPublishActivity.equals(currentActivityName)) {
                            LogUtils.e(pkgName + " \t" + currentActivityName);
                            int num = rootInActiveWindow.getChildCount();
                            AccessibilityNodeInfo scrollView = rootInActiveWindow.getChild(2);
                            AccessibilityNodeInfo relativeLayout = scrollView.getChild(0);
                            AccessibilityNodeInfo relativeLayout2 = relativeLayout.getChild(0);
                            AccessibilityNodeInfo editText = relativeLayout2.getChild(0);
                            if ("android.widget.EditText".equals(editText.getClassName())) {
                                Bundle arguments = new Bundle();
                                arguments.putCharSequence(AccessibilityNodeInfo.ACTION_ARGUMENT_SET_TEXT_CHARSEQUENCE, "这么快小龙虾上市了，想吃吗");
                                editText.performAction(AccessibilityNodeInfo.ACTION_SET_TEXT, arguments);
                                LogUtils.e(pkgName + " \t" + currentActivityName);
                                AccessibilityNodeInfo linearLayout = relativeLayout.getChild(4);
                                if ("com.ss.android.ugc.aweme:id/ayd".equals(linearLayout.getViewIdResourceName())) {
                                    int num1 = linearLayout.getChildCount();
                                    if (num >= 3) {
                                        AccessibilityNodeInfo publishFrameLayout = linearLayout.getChild(2);
                                        if ("com.ss.android.ugc.aweme:id/ase".equals(publishFrameLayout.getViewIdResourceName())) {
                                            if (publishFrameLayout.isClickable()) {
                                                performViewClick(publishFrameLayout);
//                                                disableSelf();
                                                GlobalData.isPause = true;
                                                EventBus.getDefault().post(new EventBusMessage(EventBusMessage.MSG_TYPE_GET_NEED_PUBLISH));
                                            }
                                        }
                                    }
                                }
                            }
                            //当前在多开分身
                        } else if (duokaifenshenMain.equals(currentActivityName)) {
                            LogUtils.e(pkgName + " \t" + currentActivityName);
                            AccessibilityNodeInfo shouYeRadioButton = rootInActiveWindow.getChild(1);
                            List<AccessibilityNodeInfo> main = rootInActiveWindow.findAccessibilityNodeInfosByViewId("com.bly.dkplat:id/relative_main");
                            AccessibilityNodeInfo mainLinearLayout = main.get(0);
                            int mainChildCount = mainLinearLayout.getChildCount();
                            if (mainChildCount > 2) {
                                AccessibilityNodeInfo shouYeRadioBttom = mainLinearLayout.getChild(1);
                                if ("android.widget.RadioButton".equals(shouYeRadioBttom.getClassName().toString())) {
                                    performViewClick(shouYeRadioBttom);
                                }
                            }
//                            List<AccessibilityNodeInfo> bottomLayout = rootInActiveWindow.findAccessibilityNodeInfosByViewId("com.bly.dkplat:id/bottom_banner");
//                            AccessibilityNodeInfo bottomRadioGroup = bottomLayout.get(0);
//                            String shouYe = shouYeRadioButton.getText().toString();
//                            if (!TextUtils.isEmpty(shouYe) && shouYe.equals("首页")) {
//                                if (shouYeRadioButton.isClickable()) {
//                                    performViewClick(shouYeRadioButton);
//                                }
//                            }
                        } else if (pluginConfigActivity.equals(currentActivityName)) {
                            LogUtils.e(pkgName + " \t" + currentActivityName);
                            List<AccessibilityNodeInfo> openFenShenImageView = rootInActiveWindow.findAccessibilityNodeInfosByViewId("com.bly.dkplat:id/iv_logo");
                            int num = openFenShenImageView.size();
                            if (num == 1) {
                                AccessibilityNodeInfo child = openFenShenImageView.get(0);
                                if ("android.widget.ImageView".equals(child.getClassName()) && child.isClickable()) {
                                    performViewClick(child);
                                }

                            }
                        }
                        break;
                    case AccessibilityEvent.TYPE_VIEW_CLICKED:
                        LogUtils.e(pkgName + " \t" + currentActivityName);
                        if ("com.ss.android.ugc.aweme".equals(pkgName)) {
                            if ("android.widget.TextView".equals(currentActivityName)) {
                                List<CharSequence> strList = event.getText();
                                if (strList.size() > 0) {
                                    String videoString = event.getText().get(0).toString();
                                    if ("视频".equals(videoString)) {
                                        AccessibilityNodeInfo viewPager = rootInActiveWindow.getChild(4);
                                        AccessibilityNodeInfo recycleView = viewPager.getChild(0);
                                        AccessibilityNodeInfo relativeLayout = recycleView.getChild(0);
                                        if (relativeLayout.isClickable()) {
                                            performViewClick(relativeLayout);
                                        }
                                    }
                                }
                            }
                        } else if ("com.bly.dkplat".equals(pkgName)) {
                            if ("android.widget.RadioButton".equals(currentActivityName)) {
                                List<CharSequence> strList = event.getText();
                                if (strList.size() > 0) {
                                    String videoString = event.getText().get(0).toString();
                                    if ("首页".equals(videoString)) {
//                                        AccessibilityNodeInfo centerJiaHao = rootInActiveWindow.getChild(6);
//                                        if (centerJiaHao.isClickable()) {
//                                            performViewClick(centerJiaHao);
//                                        }
                                        List<AccessibilityNodeInfo> creatLayout = rootInActiveWindow.findAccessibilityNodeInfosByViewId("com.bly.dkplat:id/iv_btn_create");
                                        int count = creatLayout.size();
                                        if (count == 1) {
                                            AccessibilityNodeInfo createBtn = creatLayout.get(0);
                                            if (createBtn.isClickable()) {
                                                performViewClick(createBtn);
                                            }
                                        }

                                    } else if ("测试".equals(videoString)) {
                                        LogUtils.e(pkgName + " \t" + currentActivityName);
                                    }
                                }
                            } else if ("android.widget.ImageView".equals(currentActivityName)) {
                                LogUtils.e(pkgName + " \t" + currentActivityName);
//                                AccessibilityNodeInfo recycleView = rootInActiveWindow.getChild(0).getChild(10);
//                                if (recycleView != null) {
//                                    int childCount = recycleView.getChildCount();
//                                    for (int i = 0; i < childCount; i++) {
//                                        AccessibilityNodeInfo child = recycleView.getChild(i);
//                                        AccessibilityNodeInfo linearlayout = child.getChild(0).getChild(0);
//                                        AccessibilityNodeInfo textView = linearlayout.getChild(0);
//                                        if ("android.widget.TextView".equals(textView.getClassName())
//                                                && "测试".equals(textView.getText().toString())) {
//                                            if (textView.isClickable()) {
//                                                performViewClick(textView);
//                                            }
//                                        }
//
//                                    }
//                                }

//                                List<AccessibilityNodeInfo> relative_main = rootInActiveWindow.findAccessibilityNodeInfosByViewId("com.bly.dkplat:id/relative_main");
//                                AccessibilityNodeInfo mainViewPager = relative_main.get(0);
//                                int count = mainViewPager.getChildCount();
//                                if (count > 0) {
//                                    AccessibilityNodeInfo mainViewPagerChild = mainViewPager.getChild(0);
//                                    int mainChild = mainViewPager.getChildCount();
//                                    if (mainChild >= 6) {
//                                        AccessibilityNodeInfo viewPagerChildChild = mainViewPagerChild.getChild(3);
//                                        if ("android.support.v4.view.ViewPager".equals(viewPagerChildChild.getClassName())) {
//                                            int num = viewPagerChildChild.getChildCount();
//                                            if (num >= 2) {
//                                                AccessibilityNodeInfo childRecyclerView = viewPagerChildChild.getChild(0);
//                                                int countChild = childRecyclerView.getChildCount();
//                                                LogUtils.d(TAG, childRecyclerView.getClassName().toString() + "  count = " + childRecyclerView.getChildCount());
//                                                if (countChild >= 3) {
//                                                    AccessibilityNodeInfo childLinearLayout = childRecyclerView.getChild(0);
//                                                    int childCount = childLinearLayout.getChildCount();
//                                                    if (childCount >= 1) {
//                                                        AccessibilityNodeInfo linearLayoutChild = childLinearLayout.getChild(0);
//                                                        if (linearLayoutChild.isClickable()) {
////                                                            performViewClick(linearLayoutChild);
//                                                        }
//                                                    }
//                                                }
//                                            }
//                                        }
//                                    }
//                                }
                                List<AccessibilityNodeInfo> rootNodeInfosByViewId = rootInActiveWindow.findAccessibilityNodeInfosByViewId("com.bly.dkplat:id/recyclerView");
                                int num = rootNodeInfosByViewId.size();
                                if (num >= 2) {
                                    AccessibilityNodeInfo recycleView1 = rootNodeInfosByViewId.get(1);
                                    //查询分身数量
                                    int size = recycleView1.getChildCount();
                                    if (size >= 1) {
                                        AccessibilityNodeInfo linearLayout = recycleView1.getChild(0).getChild(0);
                                        if (linearLayout.isClickable()) {
                                            performViewClick(linearLayout);
                                        }
//                                        int count = linearLayout.getChildCount();
//                                        for (int i = 0; i < count; i++) {
//
//                                        }

                                    }
                                }

                            }
                        }
                        break;
                    default:
                        break;
                }
            }
        }

    }

    @Override
    public void onInterrupt() {
        LogUtils.e(TAG, "--onInterrupt---");
    }

    /**
     * 模拟点击事件
     *
     * @param nodeInfo nodeInfo
     */
    public void performViewClick(AccessibilityNodeInfo nodeInfo) {
        if (nodeInfo == null) {
            return;
        }
        while (nodeInfo != null) {
            if (nodeInfo.isClickable()) {
                nodeInfo.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                break;
            }
            nodeInfo = nodeInfo.getParent();
        }
    }
}
